package org.jeecg.modules.network.network.tcp;

import com.zhouwr.common.utils.HexConvertUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;

/**
 * @program: forallcn-iotps
 * @description: 客户端测试
 * @author: zhouwr
 * @create: 2020-12-03 14:09
 * @version：1.0
 **/
public class NettyTcpClientTest {

    public static void main(String[] args) throws Exception {
        //ONE:
        //1 线程工作组
        EventLoopGroup work = new NioEventLoopGroup();

        //TWO:
        //3 辅助类。用于帮助我们创建NETTY服务
        Bootstrap b = new Bootstrap();
        b.group(work)    //绑定工作线程组
                .channel(NioSocketChannel.class)    //设置NIO的模式
                // 初始化绑定服务通道
                .localAddress(26)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel sc) throws Exception {
                        sc.pipeline().addLast(new ByteArrayEncoder());
                        sc.pipeline().addLast(new ByteArrayDecoder());
                        sc.pipeline().addLast(new ChannelOutboundHandlerAdapter());
                    }
                });

        ChannelFuture cf = b.connect("127.0.0.1", 9999).syncUninterruptibly();
        String msg = "" +
                "01 03 f4 00 c3 00 c1 00 c2 00 c0 00 bf 00 c2 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 00 c3 00 00 66 a3";

        // 0xFF 0x01 OX00
        byte[] bytes = HexConvertUtil.hexStringToBytes(msg);
        cf.channel().writeAndFlush(bytes);

        //释放连接
        cf.channel().closeFuture().sync();
        work.shutdownGracefully();
    }
}
